package cn.sinata.wanglin.neighbor.fragment;

import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;

import com.xilada.xldutils.adapter.BaseRecyclerAdapter;
import com.xilada.xldutils.fragment.BaseLazyFragment;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.view.SwipeRefreshRecyclerLayout;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import butterknife.BindView;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.adapter.VillageAdapter;
import cn.sinata.wanglin.model.Village;
import cn.sinata.wanglin.neighbor.activity.VillageNeighborActivity;
import cn.sinata.wanglin.neighbor.view.RxTextView;
import cn.sinata.wanglin.neighbor.view.SearchEditText;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.ResultData;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 *
 * Created by liaoxiang on 16/12/13.
 */

public class FindUserByVillageFragment extends BaseLazyFragment{

    @BindView(R.id.mSwipeRefreshLayout)
    SwipeRefreshRecyclerLayout mSwipeRefreshLayout;
    @BindView(R.id.tv_search)
    SearchEditText tv_search;
    private ArrayList<Village> mVillages = new ArrayList<>();
    private VillageAdapter villageAdapter;
    String keyWord="";

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_find_user_by_village;
    }

    @Override
    protected void onFirstVisibleToUser() {

        tv_search.setHint("小区名称");

        villageAdapter = new VillageAdapter(mVillages);
        mSwipeRefreshLayout.setMode(SwipeRefreshRecyclerLayout.Mode.Top);
        mSwipeRefreshLayout.setLayoutManager(new LinearLayoutManager(context));
        mSwipeRefreshLayout.addItemDecoration(new HorizontalDividerItemDecoration.Builder(context)
                .size(1)
                .color(ContextCompat.getColor(context, R.color.dividing_line_color))
                .build());
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshRecyclerLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }

            @Override
            public void onLoadMore() {

            }
        });
        mSwipeRefreshLayout.setAdapter(villageAdapter);
        villageAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Village village = mVillages.get(position);
                ActivityUtil.create(context)
                        .go(VillageNeighborActivity.class)
                        .put("id",village.getId())
                        .put("name",village.getHousingName())
                        .start();
            }
        });

        tv_search.setOnSearchActionListener(new SearchEditText.OnSearchActionListener() {
            @Override
            public void onSearch() {
                refresh();
            }
        });

        setTextChange();
    }

    private void refresh(){
        keyWord = tv_search.getText().toString();
        //重设文字触发change。
        tv_search.setText(keyWord);
        tv_search.setSelection(keyWord.length());
    }

    private void setTextChange(){
        RxTextView.textChanges(tv_search)
                .debounce(150, TimeUnit.MILLISECONDS)
                .subscribeOn(AndroidSchedulers.mainThread())
                .flatMap(new Func1<CharSequence, Observable<ResultData<ArrayList<Village>>>>() {
                    @Override
                    public Observable<ResultData<ArrayList<Village>>> call(CharSequence charSequence) {
                        keyWord = charSequence.toString();
                        if (TextUtils.isEmpty(charSequence)) {
                            return Observable.create(new Observable.OnSubscribe<ResultData<ArrayList<Village>>>() {
                                @Override
                                public void call(Subscriber<? super ResultData<ArrayList<Village>>> subscriber) {
                                    ResultData<ArrayList<Village>> resultData = new ResultData<>();
                                    resultData.setCode("SUCCESS");
                                    resultData.setMessage("关键字为空");
                                    resultData.setResultData(new ArrayList<Village>());
                                    subscriber.onCompleted();
                                    subscriber.onNext(resultData);
                                }
                            }).subscribeOn(Schedulers.io());
                        }
                        return HttpManager.searchHousing("成都市",charSequence.toString());
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultDataSubscriber<ArrayList<Village>>(this) {
                    @Override
                    public void onSuccess(String msg, ArrayList<Village> villages) {
                        mSwipeRefreshLayout.setRefreshing(false);
                        mVillages.clear();
                        if (villages.size() == 0) {
                            showToast("没有找到相关小区");
                        }
                        mVillages.addAll(villages);
                        villageAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        mSwipeRefreshLayout.setRefreshing(false);
                        setTextChange();
                    }
                });
    }

    @Override
    protected void onVisibleToUser() {

    }

    @Override
    protected void onInvisibleToUser() {

    }
}
